package com.choco.jsondb;

import com.choco.jsondb.editor.Editor;
import com.choco.jsondb.reader.Reader;

import java.io.File;
public final class JSONDB {
    public static final int KV_MODE = 0;
    public static final int ARRAY_MODE = 1;

    private Context context;
    private Reader reader;

    private JSONDB(String folder, int mode) {
        File workingFolder = new File(folder);

        if(workingFolder.exists() == false){
            workingFolder.mkdir();
        }

        context = new Context(folder, mode);
    }

    public Object get(String key){
        if(reader == null) {
            reader = Reader.get(context);
        }
        return reader.get(key);
    }

    public Editor edit(){
        /* After edit data, reader should be invalid. */
        invalidReader(context.getMode());

        return Editor.get(context);
    }

    private void invalidReader(int mode) {
        reader = null;
    }

    public Object getAll() {
        if(reader == null) {
            reader = Reader.get(context);
        }
        return reader.getAll();
    }

    public Object get() {
        if(reader == null) {
            reader = Reader.get(context);
        }
        return reader.get();
    }

    public static class Builder{
        private String folder = "";
        private int mode = KV_MODE;

        public Builder(){

        }

        public Builder folder(String folder){
            this.folder = folder;
            return this;
        }

        public Builder mode(int mode){
            this.mode = mode;
            return this;
        }

        public JSONDB connect() {
            return new JSONDB(folder, mode);
        }
    }
}
